package com.project.les;

import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import android.content.res.AssetManager;

public class FeriadosActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		this.populateDatabase();

		// Timer:
		Handler taskHandler = new Handler();
		
		final long elapse = 6000;
		Runnable t = new Runnable() {
			public void run()
			{
				Intent intent = new Intent(FeriadosActivity.this, TabsViewActivity.class);
				startActivity(intent);
			}
		};
		
		taskHandler.postDelayed(t, elapse);
	}
	
	private void populateDatabase() {
		DataHelper dh = DataHelper.getInstance();
		
		// Por enquanto este método deve ser executado após a aquisição
		// da primeira instância. Deve ser removido na versão final:
		dh.resetDatabase(this);

		dh.deleteAll();
		populateNacional(dh);
		populateState(dh);
		populateMunicipal(dh);
	}

	private void populateNacional(DataHelper dh) {
		AssetManager assetManager = getAssets();
		InputStream stream = null;
		try {
			stream = assetManager.open("nacional.txt");
			BufferedReader buffreader = new BufferedReader(
					new InputStreamReader(stream));
			String line;
			while ((line = buffreader.readLine()) != null) {
				String[] arrayString = line.split("-");
				String[] arrayDate = arrayString[0].trim().split("/");
				Integer day = new Integer(arrayDate[0]);
				Integer month = new Integer(arrayDate[1]);
				String description = arrayString[1].trim();
				DataHelper.getInstance().insert(description, "", day, month, 2011, 1, 0, "", "");
			}
			buffreader.close();
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void populateState(DataHelper dh) {
		AssetManager assetManager = getAssets();
		InputStream stream = null;
		try {
			String[] listStates = assetManager.list("estadual");
			for (int i = 0; i < listStates.length; i++) {
				stream = assetManager.open("estadual/" + listStates[i]);
				BufferedReader buffreader = new BufferedReader(
						new InputStreamReader(stream));
				String line;
				while ((line = buffreader.readLine()) != null) {
					String[] arrayString = line.split("-");
					String[] arrayDate = arrayString[0].trim().split("/");
					Integer day = new Integer(arrayDate[0]);
					Integer month = new Integer(arrayDate[1]);
					String description = arrayString[1].trim();
					DataHelper.getInstance().insert(description, "", day, month, 2011, 0, 1,
							accentuatedStateFromFilename(
									listStates[i].substring(0,
									listStates[i].length() - 4)), "");
				}
				buffreader.close();
				stream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Retorna o nome do estado com a acentuação correta.
	 * Ex.: "Paraiba" retorna "Paraíba", com acento no "i".
	 *  
	 * @return O nome do estado com a acentuação correta.
	 */
	private String accentuatedStateFromFilename(String fileName) {
		Map<String, String> mapList = new HashMap<String, String>();
		mapList.put("Acre", "Acre");
		mapList.put("Alagoas", "Alagoas");
		mapList.put("Amapa", "Amapá");
		mapList.put("Amazonas", "Amazonas");
		mapList.put("Bahia", "Bahia");
		mapList.put("Ceara", "Ceará");
		mapList.put("Distrito Federal", "Distrito Federal");
		mapList.put("Espirito Santo", "Espírito Santo");
		mapList.put("Goias", "Goiás");
		mapList.put("Maranhao", "Maranhão");
		mapList.put("Mato Grosso do Sul", "Mato Grosso do Sul");
		mapList.put("Mato Grosso", "Mato Grosso");
		mapList.put("Minas Gerais", "Minas Gerais");
		mapList.put("Para", "Pará");
		mapList.put("Paraiba", "Paraíba");
		mapList.put("Parana", "Paraná");
		mapList.put("Pernambuco", "Pernambuco");
		mapList.put("Piaui", "Piauí");
		mapList.put("Rio de Janeiro", "Rio de Janeiro");
		mapList.put("Rio Grande do Norte", "Rio Grande do Norte");
		mapList.put("Rio Grande do Sul", "Rio Grande do Sul");
		mapList.put("Rondonia", "Rondônia");
		mapList.put("Roraima", "Roraima");
		mapList.put("Santa Catarina", "Santa Catarina");
		mapList.put("Sao Paulo", "São Paulo");
		mapList.put("Sergipe", "Sergipe");
		mapList.put("Tocantins", "Tocantins");
		
		return mapList.get(fileName);
	}
	
	private void populateMunicipal(DataHelper dh) {
		AssetManager assetManager = getAssets();
		InputStream stream = null;
		try {
			String[] listStates = assetManager.list("municipal");
			for (int i = 0; i < listStates.length; i++) {
				stream = assetManager.open("municipal/" + listStates[i]);
				BufferedReader buffreader = new BufferedReader(
						new InputStreamReader(stream));
				String line;
				String city = "";
				while ((line = buffreader.readLine()) != null) {
					String[] arrayString = line.split("-");
					if(!line.contains("-") && line.trim().length() != 0) {
						city = line;						
					}
					else if(line.contains("-")) {
						String[] arrayDate = arrayString[0].trim().split("/");
						Integer day = new Integer(arrayDate[0]);
						Integer month = new Integer(arrayDate[1]);
						String description = arrayString[1].trim();
						DataHelper.getInstance().insert(description, "", day, month, 2011, 0, 0,
								listStates[i].substring(0,
										listStates[i].length() - 4), city);
					}
				}
				buffreader.close();
				stream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
